// subPages/health/healthShopDetails/healthShopDetails.js
const app = getApp();
var util =  require('../../../utils/util.js');
import share from '../../../utils/share';
import { base64Src } from '../../../utils/base64Src.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentSwiper: 0,
    buyNum: 1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    let id = ''
    console.log(options)
    
    if(options.id){
      id = options.id
    }else if(options.scene){
      id = decodeURIComponent(options.scene)
    }
    if(app.globalData.userId){
      that.setData({
        userId: app.globalData.userId
      })
      //获取商品详情
      util.getAjax(app.globalData.apiUrl +'/get_community_health_shop_product_content',that.getData,{id: options.id,user_id: that.data.userId})
    }else{
      app.userIdCallback = userId => {
        if (userId != '') {
          that.setData({
            userId: userId
          });
          //获取商品详情
          util.getAjax(app.globalData.apiUrl +'/get_community_health_shop_product_content',that.getData,{id: options.id,user_id: that.data.userId})
        }
      }
    }
  },

  //获取商品数据
  getData(res){
    var that = this;
    console.log(res)
    if(res.data){
      that.setData({
        shopList: res.data,
        isDiscount: res.data.xsqg_price?true:false,
        allPay: res.data.pay_yes?res.data.pay_yes:0,//总销量
        price: res.data.price?res.data.price:'-',//价格
        discountPrice: res.data.xsqg_price?res.data.xsqg_price:'',//打折价
        isActivity: res.data.xsqg_price?true:false,//是否活动
        productName: res.data.product_name?res.data.product_name:'-',//商品名称
        city: res.data.city?res.data.city:'天津',//城市
        content: res.data.content?res.data.content:'-',//商品介绍
        goodsBannerList: res.data.top_img,//商品banner图片
        goodsBanner: res.data.top_img[0],//商品banner图片
        goodsImgList: res.data.content_img,//商品详情图片
        freight:res.data.yunfei?res.data.yunfei:'0.00',//运费
        shopName: res.data.shop_content.shop_name?res.data.shop_content.shop_name:'',//店铺名称
        shopImg: res.data.shop_content.shop_img?res.data.shop_content.shop_img:'',//店铺头像
        shopContent: res.data.shop_content.content?res.data.shop_content.content:'',//店铺简介
        shopPhone: res.data.shop_content.shop_phone?res.data.shop_content.shop_phone:'',//店铺头像
        parameterList: res.data.canshu?res.data.canshu:[],//参数
        parameterNameList: that.setParameter(res.data.canshu),
        isTell: res.data.tell.length!=0?true:false,
        commentContent: res.data.tell.content?res.data.tell.content:'-',//
        commentUserName: res.data.tell.user_name?res.data.tell.user_name:'-',
        commentUserImg: res.data.tell.user_head_img?res.data.tell.user_head_img:'',
        tellAll: res.data.tell_all?res.data.tell_all: 0,//评论总数
        shopId: res.data.shop_id,//商户id
        id: res.data.id,//商品id
        cartNum: res.data.buycar?res.data.buycar.num: 0,
        endTime: res.data.no_time?res.data.no_time:'',
        inventory: res.data.pay_no
      })
      if(that.data.isActivity && that.data.endTime){
        that.countdown(that.data.endTime)
      }
    }
  },

  //单个倒计时，适用用于单个商品的倒计时
  countdown:function(time) {
    var that = this
    var endTime = new Date(String(time).replace(/-/g,"/")).getTime() || [];//倒计时的结束时间
    var nowTime = new Date().getTime();//当前时间
    var total_micro_second = endTime - nowTime || []
    if (total_micro_second <= 0) {
      that.setData({
        isEnd: true,
        isActivity: false,
      });
      return;
    }
    // 渲染倒计时时钟
    var count = util.dateformat(total_micro_second)//剩余的微秒
    var countList = []
    for(var i=0;i<count.length;i++)
    {
      countList.push(count.charAt(i))
    }
    that.setData({
      countList: countList
    });
    setTimeout(function () {
      that.countdown(that.data.endTime);
    }, 1000)
  },

  //设置参数
  setParameter:function(list){
    if(list&&list.length!=0){
      var arr = ''
      for(var i in list){
        arr += list[i].name + ' '
      }
      return arr
    }
    return ''
  },

  swiperChange:function(e){
    this.setData({
      currentSwiper: e.detail.current
    })
  },

  //评论查看全部按钮
  evaluateAllBtn:function(){
    if(this.data.tellAll && this.data.tellAll > 0){
      wx.navigateTo({
        url: '/subPages/health/allComments/allComments?id=' + this.data.id
      })
    }else{
      util.showModal('提示','暂无评论')
    }
  },

  //点击购物车
  shopCartBtn:function(){
    wx.navigateTo({
      url: '/subPages/health/shopCart/shopCart'
    })
  },

  //点击图片
  imgBtn:function(e){
    var list = e.currentTarget.dataset.list;
    var index = e.currentTarget.dataset.index;
    let arr = []
    for(var i in list){
      arr.push(list[i].banner_img)
    }
    wx.previewImage({
      urls: arr,
      current: arr[index]
    })
  },

  //加入购物车
  inCartBtn:function(){
    var that = this
    if(that.data.isActivity){
      util.showToast('商品限时抢购，只支持立即购买','none',2000)
      return
    }
    if(app.globalData.userId){
      that.setData({
        userId: app.globalData.userId
      })
      that.inCart()
    }else{
      app.userIdCallback = userId => {
        if (userId != '') {
          that.setData({
            userId: userId
          });
          that.inCart()
        }
      }
    }
  },

  //加入购物车
  inCart:function(){
    var that = this
    var cartNum = Number(that.data.cartNum) + 1
    util.getAjax(app.globalData.apiUrl +'/operation_community_health_shop_product_buycar',function(res){
      if(res.data==1){
        util.showToast('添加成功，在购物车等亲~','none',2000)
        that.setData({
          cartNum: cartNum
        })
      }
    },{type: 1,shop_id:that.data.shopId,product_id: that.data.id,user_id: that.data.userId,num: cartNum,price: that.data.discountPrice!=''?that.data.discountPrice: that.data.price,})
  },

  //参数按钮
  parameterBtn:function(e){
    if(this.data.parameterNameList){
      var currentStatus = e.currentTarget.dataset.status;
      this.parameterAnim(currentStatus);
    }else{
      util.showToast('暂无参数','none',1000)
    }
  },

  //完成按钮
  OkBtn:function(){
    var currentStatus = 'complete';
    this.parameterAnim(currentStatus);
  },

  //动画部分
  parameterAnim: function (currentStatus) {
    // 第1步：创建动画实例
    var animation = wx.createAnimation({
      duration: 200,  //动画时长
      timingFunction: "linear", //线性
      delay: 0  //0则不延迟
    });

    // 第2步：这个动画实例赋给当前的动画实例
    this.animation = animation;

    // 第3步：执行第一组动画：Y轴偏移240px后(盒子高度是400px)，停
    animation.translateY(500).step();

    // 第4步：导出动画对象赋给数据对象储存
    this.setData({
      parameterAnim: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画
    setTimeout(function () {
      // 执行第二组动画：Y轴不偏移，停
      animation.translateY(0).step()
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
      this.setData({
        parameterAnim: animation
      })

      //完成
      if (currentStatus == "complete") {
        this.setData(
          {
            isParameter: false,
          }
        );
      }
    }.bind(this), 200)

    // 显示抽屉
    if (currentStatus == "open") {
      this.setData(
        {
          isParameter: true,
          parameterTitle: '参数',
        }
      );
    }
  },

  //分享按钮
  shareBtn:function(e){
    var currentStatus = e.currentTarget.dataset.status;
    this.shareAnim(currentStatus);
  },

  //取消按钮
  cancelBtn:function(e){
    var type = e.currentTarget.dataset.type;
    switch (type) {
      case 'share':
        var currentStatus = 'cancel';
        this.shareAnim(currentStatus);
        break;
      case 'friends':
        this.setData({
          isFriends: false
        })
        break;
    }
  },

  //动画部分
  shareAnim: function (currentStatus) {
    // 第1步：创建动画实例
    var animation = wx.createAnimation({
      duration: 200,  //动画时长
      timingFunction: "linear", //线性
      delay: 0  //0则不延迟
    });

    // 第2步：这个动画实例赋给当前的动画实例
    this.animation = animation;

    // 第3步：执行第一组动画：Y轴偏移240px后(盒子高度是400px)，停
    animation.translateY(130).step();

    // 第4步：导出动画对象赋给数据对象储存
    this.setData({
      shareAnim: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画
    setTimeout(function () {
      // 执行第二组动画：Y轴不偏移，停
      animation.translateY(0).step()
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
      this.setData({
        shareAnim: animation
      })

      //完成
      if (currentStatus == "cancel") {
        this.setData(
          {
            isShare: false,
          }
        );
      }
    }.bind(this), 200)

    // 显示抽屉
    if (currentStatus == "open") {
      this.setData(
        {
          isShare: true,
        }
      );
    }
  },

  //朋友圈按钮
  friendsCircleBtn:function(){
    var that = this
    //获得二维码
    wx.request({
      url: app.globalData.apiUrl +'/Api/GetUser/getWxcode',
      data: {
        page: 'subPages/health/healthShopDetails/healthShopDetails',
        scene: that.data.id
      },
      method: 'get',
      header: {
        'content-type': 'application/json' //默认值
      },
      success: function (res) {
        // console.log(res)
        base64Src(res.data, code => {
          // console.log(code) // 返回图片地址，直接赋值到image标签即可
          let BannerImg = that.data.goodsBanner.banner_img.replace('http:','https:');
          that.setData({
            isFriends: true,
            codeimg: res.data,
            template: new share().palette(BannerImg,that.data.price,that.data.productName,that.data.content,code),
          })
        })
      },
      fail: function (res) {
        console.log("失败",res);
      }
    })
  },

  onImgOK(e) {
    this.setData({
      imagePath: e.detail.path
    })
  },

  //保存图片
  savePicBtn:function(){
    var that = this
    wx.getSetting({
      success(res) {
        // console.log(res)
        //没有授权
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope:'scope.writePhotosAlbum',
            success() {
              console.log('授权成功')
            }
          })
        }
      }
    })
    wx.saveImageToPhotosAlbum({
      filePath: this.data.imagePath,
      success:function(res) {
        util.showToast('保存图片成功','success',1000)
        that.setData({
          isFriends: false
        })
        let currentStatus = 'cancel';
        that.shareAnim(currentStatus);
      },
      fail: function (err) {
        // console.log(err)
        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
          wx.showModal({
            title: '提示',
            content: '请重新授权保存相册',
            showCancel: false,
            success:modalSuccess=>{
              wx.openSetting({
                success(settingdata) {
                  // console.log("settingdata", settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    util.showModal('提示','获取权限成功,再次点击图片即可保存')
                  } else {
                    util.showModal('提示','获取权限失败，将无法保存到相册哦~')
                  }
                },
                fail(err) {
                  // console.log("err",err)
                }
              })
            }
          })
        }
      },
    })
  },

  // close:function(){
  //   this.setData({
  //     isShare: false,
  //     template: {},
  //   })
  // },

  //立即购买
  buyBtn:function(e){
    var that = this
    if(that.data.inventory == 0){
      //库存空
      util.showModal('提示','当前商品已售罄，请联系商家')
      return
    }
    if(that.data.shopList){
      var currentStatus = e.currentTarget.dataset.status;
      that.buyNumAnim(currentStatus);
    }
    
  },

  //完成按钮
  OkBuyBtn:function(){
    var that = this
    var currentStatus = 'complete';
    that.buyNumAnim(currentStatus);
    if(that.data.buyNum == 0){
      util.showToast('请选择购买数量','none',1000)
      return
    }
    wx.navigateTo({
      url: '/subPages/health/submitOrders/submitOrders?list=' + JSON.stringify(that.data.shopList) + '&type=' + 1 + '&num=' + that.data.buyNum
    })
  },

  //关闭按钮
  closeBtn:function(){
    var currentStatus = 'complete';
    this.buyNumAnim(currentStatus);
  },

  //动画部分
  buyNumAnim: function (currentStatus) {
    // 第1步：创建动画实例
    var animation = wx.createAnimation({
      duration: 200,  //动画时长
      timingFunction: "linear", //线性
      delay: 0  //0则不延迟
    });

    // 第2步：这个动画实例赋给当前的动画实例
    this.animation = animation;

    // 第3步：执行第一组动画：Y轴偏移240px后(盒子高度是400px)，停
    animation.translateY(300).step();

    // 第4步：导出动画对象赋给数据对象储存
    this.setData({
      buyNumAnim: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画
    setTimeout(function () {
      // 执行第二组动画：Y轴不偏移，停
      animation.translateY(0).step()
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
      this.setData({
        buyNumAnim: animation
      })

      //完成
      if (currentStatus == "complete") {
        this.setData(
          {
            isBuy: false,
          }
        );
      }
    }.bind(this), 200)

    // 显示抽屉
    if (currentStatus == "open") {
      this.setData(
        {
          isBuy: true,
        }
      );
    }
  },

  //增减数量
  modifyNumber:function(e){
    var that = this
    var type = e.currentTarget.dataset.type
    var buyNum = that.data.buyNum
    switch (type) {
      case 'add':
        buyNum ++
        break;
      case 'subtract':
        if(that.data.buyNum != 1){
          buyNum --
        }
        break;
    }
    that.setData({
      buyNum: buyNum
    })
  },

  //联系商家
  phoneBtn:function(e){
    var phone = e.currentTarget.dataset.phone
    if(phone){
      wx.makePhoneCall({
        phoneNumber: phone
      })
    }else{
      util.showModal('提示','电话不存在')
      return
    }
  },

  //阻止穿透
  preventTouchMove: function () {
    return;
  },

  //回到顶部
  goTop: function (e) {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },

  // 获取滚动条当前位置
  onPageScroll: function (e) {
    // console.log(e)
    if (e.scrollTop > 600) {
      this.setData({
        isTop: true
      });
    } else {
      this.setData({
        isTop: false
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    if(that.data.id){
      if(that.data.userId){
        util.getAjax(app.globalData.apiUrl +'/Api/Communityhealth/get_buycar_have_product',function(res){
          // console.log(res)
          if(res.data){
            that.setData({
              cartNum: res.data.num
            })
          }else{
            that.setData({
              cartNum: 0
            })
          }
        },{id: that.data.id,user_id: that.data.userId})
      }else{
        app.userIdCallback = userId => {
          if (userId != '') {
            that.setData({
              userId: userId
            });
            util.getAjax(app.globalData.apiUrl +'/Api/Communityhealth/get_buycar_have_product',function(res){
              if(res.data){
                that.setData({
                  cartNum: res.data.num
                })
              }else{
                that.setData({
                  cartNum: 0
                })
              }
            },{id: that.data.id,user_id: that.data.userId})
          }
        }
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    if(res.form == 'button'){

    }
    return {
      title: this.data.productName,
      path: `subPages/health/healthShopDetails/healthShopDetails?id=${this.data.id}` // 分享后打开的页面
    }
  }
})